
function getFaq(pid) {
	get("faq", {pid:pid}, false, function (resp) {
		var messages = resp;
		showFaqList(messages);
	});
}
function getButton(pid) {
	get("button", {pid:pid}, false, function (resp) {
		var list = resp;
		showButtonList(list);
	});
}
function getCrm() {
	get("crm", {pid:pid}, false, function (resp) {
		crm = resp;
		SETTING_FILE_PATH = "../file/load.do?method=get&id=" + crm.id + "&bizType=SETTING&fileName=";
		MSG_FILE_PATH = "../file/load.do?method=get&id=" + crm.id + "&bizType=CHAT&fileName=";
	});
}
function getSetting(pid) {
	get("setting", {pid:pid}, false, function (resp) {
		setting = resp;
		showSetting(setting);
	});
}
function getLog(pid, manual) {
	var pageCount = 15;
	if (setting.historyMessagePolicy == 0) {
		return;
	}
	if (!vl(pgData[pid])) {
		pgData[pid] = 1;
	} else {
		pgData[pid] = pgData[pid] + 1;
	}
	get("log", {start:pgData[pid], count:pageCount, pid:pid}, false, function (resp) {
		var messages = resp;
		for (var v = 0; v < messages.length; v++) {
			var message = messages[v];
			showChatMessge(message, "prepend");
		}
		if (messages.length > 0) {
			showMoreMessage(pid);
		}
		if (messages.length < pageCount) {
			hideMoreMessage();
		}
		if (!vl(manual)) {
			toBottom();
		}
	});
}
function getGroupList() {
	get(MESSAGE_EVENT.GET_GROUP, {pid:pid}, false, function (resp) {
		var messages = resp;
		if (messages.list.length == 1) {
			enterGroup(messages.list[0].id);
		} else {
			showGroupList(messages);
			toBottom();
			showSessionStep(CLIENT_SESSION_STEP.LIST_GROUP);
		}
	});
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function enterGroup(groupId) {
	showTip(TEXT.REQUESTING);
	var data = {value:groupId, event:MESSAGE_EVENT.ENTER_GROUP, pid:pid};
  	//发送消息之后立即获取返回
	send(data, function (resp) {
		if (resp.code == 0) {
			hideTip();
			get();
		} else {
			showLayer(TEXT.DO_ERROR);
		}
	});
}
function selectQuestion(questionId, text) {
	doSend(text, questionId);
	if($("#tab-content-div-0").is(":hidden")) {//小窗口在选择常见问题之后关闭
		layer.closeAll();
	}
}
function isTalking(step) {
	return step == CLIENT_SESSION_STEP.SELF || step == CLIENT_SESSION_STEP.AGENT || step == CLIENT_SESSION_STEP.QUEUE;
}
//处于结束
function isEnd(step) {
	return step == CLIENT_SESSION_STEP.CANCEL_QUEUE || step == CLIENT_SESSION_STEP.END || step == CLIENT_SESSION_STEP.QUEUE_OVER_TIME;
}
function canSelectWorkgroup(step) {
	return step == CLIENT_SESSION_STEP.LOGIN || step == CLIENT_SESSION_STEP.SELF;
}
function doSend(sendContent, value2, multiType0) {
	var session = sessions[pid];
	if (!vl(session)) {
		showLayer(TEXT.REFRESH_TO_LOAD);
		return;
	} else {
		if (!isTalking(session.step)) {
			showLayer(TEXT.ERROR_STATUS);
			return;
		}
	}
	var data = {event:MESSAGE_EVENT.CHAT, time:TEXT.SENDING, value:sendContent, pid:pid, senderRole:SENDER_ROLE.VISITOR};
	if (value2) {
		data.value2 = value2;
	}
	if (multiType0) {
		data.multiType = multiType0;
	} else {
		data.multiType = MULIT_TYPE.TEXT;
	}
	send(data, function (resp) {
		showChatMessge(data);
		toBottom();
		var v = $("#Time" + resp.id);
		if (v) {
			if (resp.code == 0) {
				v.html(resp.time);
			} else {
				v.html(resp.time + TEXT.SEND_FAIL);
			}
		}
		//发送消息之后即可拉取一次【自助服务是通过推送消息进行回复的】
		get();
	});
}
function cancelQueue() {
	layer.confirm(TEXT.CONFIRM_CANCEL_QUEUE, {title:TEXT.CONFIRM_TITLE, shadeClose:true, btn:[TEXT.CONFIRM, TEXT.CANCEL]}, function () {
		var data = {event:MESSAGE_EVENT.CANCEL_QUEUE, pid:pid};
		send(data, function (resp) {
			//发送消息之后即可拉取一次【自助服务是通过推送消息进行回复的】
			if (resp.code == 0) {
				get();
			} else {
				showLayer(TEXT.DO_ERROR);
			}
		});
		layer.closeAll();
	});
}
//执行实际的关闭窗口
function realCloseWindow(time){
	if(windowOpenType == "P") {//弹窗模式则采用window close
		if(time) {
			setInterval(function () {
				window.close();
			}, time);
		} else {
			window.close();
		}
	} else {//DIV模式则回传消息
		postMessage({event:"close"});
	}
}

//点击关闭窗口的图标
function endSessionOnTop() {
	if(disconnection) {
		realCloseWindow();
	} else {
		//处于结束状态则直接关闭
		if(sessions[pid].step == CLIENT_SESSION_STEP.LOGIN || isEnd(sessions[pid].step)) {
			realCloseWindow();
		} else {
			//这个参数在后面有用：收到END的时候关闭，或者满意度结束/取消之后关闭
			closingWindow = true;
			endSession();
		}
	}
}

function minWidowOnTop() {
	postMessage({event:"min"});
}

function endSession() {
	layer.confirm(TEXT.CONFIRM_END_SESSION, {title:TEXT.CONFIRM_TITLE, shadeClose:true, btn:[TEXT.CONFIRM, TEXT.CANCEL]}, function () {
		$("#btnEnd").hide();
		var data = {event:MESSAGE_EVENT.END_SESSION, pid:pid};
		send(data, function (resp) {
			//发送消息之后即可拉取一次【自助服务是通过推送消息进行回复的】
			if (resp.code == 0) {
				get();				
			} else {
				showLayer(TEXT.DO_ERROR);
			}
		});
		layer.closeAll();
	});
}
function transferManual() {
	//当前操作的会话
	var session = sessions[pid];
	//如果还没有开始会话，或者会话还没有技能组，那么就显示技能组进行选择
	if (!vl(session) || !vl(session.requestGroup)) {
		getGroupList();
	} else {//自助聊天转人工
		if (canSelectWorkgroup(session.step)) {
			var data = {value:session.requestGroup, event:MESSAGE_EVENT.ENTER_GROUP, pid : pid};
			send(data, function (resp) {
				//发送消息之后即可拉取一次【自助服务是通过推送消息进行回复的】
				get();
				if(resp.code == 0) {
				} else {
					//非服务时间
					if(resp.msg == MESSAGE_NOTIFY.NO_SERVICE_TIME) {
						showLayer(TEXT.NO_SERVICE_TIME);
					} else {
						showLayer(TEXT.DO_ERROR);
					}
				}
			});
		} else {
			showLayer(TEXT.ERROR_STATUS);
		}
	}
}
function handlerNotify(message) {
	if (message.notify == MESSAGE_NOTIFY.QUEUE_OVER_TIME) {//排队已经被放弃
		sessions[pid].step = CLIENT_SESSION_STEP.QUEUE_OVER_TIME;
		showSessionStep(sessions[pid].step);
		stopQueueDuration();
		return;
	} else if (message.notify == MESSAGE_NOTIFY.QUEUE_CANCEL_ED) {//排队已经取消
		sessions[pid].step = CLIENT_SESSION_STEP.CANCEL_QUEUE;
		showSessionStep(sessions[pid].step);
		stopQueueDuration();
		return;
	} else if (message.notify == MESSAGE_NOTIFY.END_SESSION) {//服务端发回来的结束会话通知
		sessions[pid].step = CLIENT_SESSION_STEP.END;
		showSessionStep(sessions[pid].step);
		return;
	} else if (message.notify == MESSAGE_NOTIFY.AG_SEND_SATISFY) {//服务端发起的满意度评价邀请
		showSatisfy();
		return;
	}
	hideTip();
	var text = TEXT[message.notify];
	if (message.notify == MESSAGE_NOTIFY.MEMBER_STATUS) {
		if (message.object.status == MEMBER_STATUS.ONLINE) {
			text = TEXT.AGENT_SERVICING;
			showTip(text.replace("XX", message.object.memberNickname));
			$("#agent-signature").html(message.object.memberNickname);
		} else {
			if (message.object.status == MEMBER_STATUS.OFFLINE) {
				text = TEXT.AGENT_NO_SERVICING;
				showTip(text);
			} else {
				if (message.object.status == MEMBER_STATUS.END) {
					text = TEXT.AGENT_END_SESSION;
					showTip(text);
				}
			}
		}
	} else if (message.notify == MESSAGE_NOTIFY.QUEUE_POSITION) {
		//排队不允许说话时，取消排队和留言的链接放在上面
		if(setting.queueTalkingPolicy == 0) {
			text = TEXT.QUEUE_POSITION_NO_LINK;
		} else {//排队可以许说话时，取消排队和留言的链接放下面
			text = TEXT.QUEUE_POSITION;
		}
		var js = JSON.parse(message.text);
		text = text.replace("N", js.n);
		text = text.replace("X", timeToString(js.x, 1));
		showTip(text, "noHide");
		queueDuration = js.x;
		countQueueDuration();
		if (queueDurationTimer == null) {
			queueDurationTimer = setInterval(countQueueDuration, 1000);
		}
	} else if (message.notify == MESSAGE_NOTIFY.AUTO_TO_MANUAL) {
		showTip(message.text);
		transferManual();
	} else {
		if (vl(message.text)) {
			showTip(message.text);
		} else {
			if (text) {
				showTip(text);
			}
		}
	}
}
var queueDurationTimer;
var queueDuration = 0;
function countQueueDuration() {
	$("#queueDuration").html(timeToString(queueDuration, 1));
	queueDuration++;
	if (queueDuration > setting.queueLimit * 60 + 1) {
		clearTimeout(queueDurationTimer);
		get();
	}
}
function stopQueueDuration() {
	if(queueDurationTimer) {
		clearTimeout(queueDurationTimer);
	}
	hideTip();
}
function uploadFile() {
	if ($("#sendFile").val() == "") {
		return;
	}
	var params = {bizType:"CHAT", uploadUrl:UPLOAD_URL, id : crm.id};
	MyUpload.uploadFile(params, $("#sendFileForm"), function (resp) {
		if (resp.code == 0) {
			doSend(JSON.stringify(resp), "", MULIT_TYPE.FILE);
		} else {
			showLayer(TEXT.DO_ERROR + resp.msg);
		}
		$("#file").val("");
	});
}
function submitLw() {
	var name = $("#LW_NAME").val();
	var phone = $("#LW_PHONE").val();
	var memo = $("#LW_MEMO").val();
	if (name == "" || phone == "" || memo == "") {
		showLayer(TEXT.INPUT_FULL_INFO);
		return;
	}
	var qq = $("#LW_QQ").val();
	var email = $("#LW_EMAIL").val();
	var data = {event:MESSAGE_EVENT.LEAVEWORD, pid:pid, name:name, phone:phone, memo:memo, qq:qq, email:email, value:"留言"};
	send(data, function (resp) {
		if (resp.code == 0) {
			toggleLw();
			showLayer(TEXT.THANKS_LEAVEWORD);
		} else {
			showLayer(TEXT.DO_ERROR);
		}
	});
}



function initEvents() {
	$(function () {
		$("#satisfyBtn").on("click", function (e) {
			showSatisfy();
		});
		$("#cutBtn").on("click", function (e) {
			showLayer(TEXT.CUT_TIP, 6000);
		});
		$("#audioBtn").on("click", function (e) {
			recordAudio();
		});
		$("#cancelRecord").on("click", function (e) {
			cancelRecordAudio();
		});
		$("#sendRecord").on("click", function (e) {
			sendRecordAudio();
		});
		$("#stopRecord").on("click", function (e) {
			cancelRecordAudio(true);
		});		
		$("#faqBtn").on("click", function (e) {
			showFaqList2();
		});
		$('#emojiBtn').bind({
			click : function(event) {
				isSelectEmotion = true;
				if (!$('#wechatEmotion').is(':visible')) {
					$(this).wechatEmotion('#textarea', keditor);
					if (event.stopPropagation) {
						event.stopPropagation();
					} else if (window.event) {
						window.event.cancleBubble = true;
					}
				}
			}
		});		
	});
}